import org.apache.zookeeper.ZooKeeper;
import org.san.ZooKeeperReenterantLock;

import java.util.concurrent.TimeUnit;

/**
 * @author gaodong
 * @version 1.0
 * @date 2021/6/9 10:10
 */
public class ZkLock {
    public static void main(String[] args) throws Exception {
        String zkConStr = "127.0.0.1:2181";
        String path = "/zklock2";

        ZooKeeper zooKeeper = new ZooKeeper(zkConStr, 5000, null);

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1; j++) {
                    ZooKeeperReenterantLock lock = new ZooKeeperReenterantLock(zooKeeper, path);
                    try {
                        if (!lock.acquire(5, TimeUnit.SECONDS)) {
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }

                    System.out.println(Thread.currentThread().getName() + " start");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                    }

                    try {
                        System.out.println(Thread.currentThread().getName() + " release");
                        lock.release();
                    } catch (Exception e) {
                    }
                }

            }, String.valueOf(i)).start();
        }

    }
}
